const app = getApp();

Page({
    data: {
        oldPassword: '',
        newPassword: '',
        confirmNewPassword: ''
    },
    onLoad: function () {
        // 页面加载时的逻辑
    },
    onOldPasswordChange(e) {
        this.setData({
            oldPassword: e.detail
        });
    },
    onNewPasswordChange(e) {
        this.setData({
            newPassword: e.detail
        });
    },
    onConfirmNewPasswordChange(e) {
        this.setData({
            confirmNewPassword: e.detail
        });
    },
    changePassword() {
        const { oldPassword, newPassword, confirmNewPassword } = this.data;
        if (!oldPassword || !newPassword || !confirmNewPassword) {
            wx.showToast({
                title: '请填写完整信息',
                icon: 'none'
            });
            return;
        }
        if (newPassword !== confirmNewPassword) {
            wx.showToast({
                title: '新密码与确认密码不一致',
                icon: 'none'
            });
            return;
        }
        const userId = app.globalData.user.id || 6; // 假设全局变量中存储了用户ID
        wx.request({
            url: `http://localhost:8080/hqy/users/updatePassword`,
            method: 'POST',
            data: {
                userId: userId,
                oldPassword: oldPassword,
                newPassword: newPassword
            },
            header: {
                'Content-Type': 'application/x-www-form-urlencoded' // 修改请求头
            },
            success: (res) => {
                if (res.statusCode === 200 && res.data.code === 200) {
                    wx.showToast({
                        title: '密码修改成功',
                        icon: 'success',
                        duration: 2000
                    });
                    app.globalData.user.password = newPassword;
                    setTimeout(() => {
                        wx.navigateBack(); // 返回上一页
                    }, 2000);
                } else {
                    wx.showToast({
                        title: res.data.message || '密码修改失败',
                        icon: 'none'
                    });
                }
            },
            fail: (err) => {
                console.error('请求失败:', err);
                wx.showToast({
                    title: '网络请求失败',
                    icon: 'none'
                });
            }
        });
    },
    cancelChange() {
        wx.navigateBack(); // 返回上一页
    },
    navigateBack() {
        wx.navigateBack(); // 返回上一页
    }
});